package com.uit.gis.pojo;

import com.uit.gis.util.JsonData;
import com.uit.gis.util.Util.SpatialType;

import processing.data.JSONArray;
import processing.data.JSONObject;

public class Triangle extends Shape {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	int clickCount = 0;
	JSONArray arrayJson = new JSONArray();

	@Override
	public void setup() {
		spatialType = SpatialType.TRIANGLE;
		background(255);
	}

	public void draw() {
		if (!continueDraw) {
			return;
		}
		background(255);
		stroke(0);
		noFill();

		beginShape();
		for (int i = 0; i < arrayJson.size(); i++) {
			JSONObject vertex = arrayJson.getJSONObject(i);
			vertex(vertex.getInt("x"), vertex.getInt("y"));
		}

		if (arrayJson.size() > 0 && arrayJson.size() < 3) {
			endShape();
			stroke(255);
			JSONObject vertex = arrayJson.getJSONObject(arrayJson.size() - 1);
			line(mouseX, mouseY, vertex.getInt("x"), vertex.getInt("y"));
		} else if (arrayJson.size() == 3) {
			JSONObject vertex = arrayJson.getJSONObject(0);
			vertex(vertex.getInt("x"), vertex.getInt("y"));
			endShape();
		}
	}

	public void mousePressed() {

		if (!continueDraw) {
			return;
		}
		if (clickCount <= 2) {
			clickCount++;
			JSONObject vertex = new JSONObject();
			vertex.setInt("x", mouseX);
			vertex.setInt("y", mouseY);
			arrayJson.append(vertex);
		}
		// else {
		// arrayJson = new JSONArray();
		// clickCount = 0;
		// }
	}

	@Override
	public void mouseClicked(processing.event.MouseEvent e) {

		if (e.getButton() == processing.core.PConstants.RIGHT
				&& clickCount == 3) {
			// saveJSONArray(arrayJson, "triangle.json");
			saveToTextFile();
			continueDraw = false;
		} else if (e.getButton() == processing.core.PConstants.LEFT
				&& clickCount == 3 && !continueDraw) {
			arrayJson = new JSONArray();
			clickCount = 0;
			continueDraw = true; // resume
		}
	}

	@Override
	public void saveToTextFile() {
		// TODO Auto-generated method stub
		saveJSONArray(arrayJson, getSavingPath());
		super.saveToTextFile();
	};

	@Override
	public JsonData loadDataFromFile() {
		// TODO Auto-generated method stub
		JSONArray jsonArray = loadJSONArray(getSavingPath());
		JsonData jsonData = new JsonData(jsonArray, null);
		return jsonData;
	};
}
